package archer.framework.security.utils;

import archer.framework.security.ArcherSecurityModule;
import archer.framework.security.token.Subject;
import archer.framework.security.token.Token;
import archer.framework.security.token.TokenManager;
import archer.framework.security.token.impl.DefaultTokenCreator;
import archer.framework.utils.ContextUtils;
import archer.framework.utils.MapUtils;
import archer.framework.utils.ServletUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author christ
 * @date 2016/5/31
 */
public class TokenUtils {

    /**
     * 获得当前请求对应的token，可能为空
     *
     * @return
     */
    public static Token getToken() {

        return getToken(ServletUtils.getCurrentRequest());
    }

    /**
     * 获得请对对应的token，可能为空
     *
     * @param request
     * @return
     */
    public static Token getToken(HttpServletRequest request) {

        return request == null
                ? null
                : getTokenManager().find(request.getParameter(ArcherSecurityModule.tokenField));
    }

    /**
     * 刷新当前请求对应的token
     */
    public static void touchToken() {

        touchToken(ServletUtils.getCurrentRequest());
    }

    /**
     * 刷新请求对应的token
     *
     * @param request
     */
    public static void touchToken(HttpServletRequest request) {

        getTokenManager().touch(request.getParameter(ArcherSecurityModule.tokenField));
    }


    /**
     * 创建token
     *
     * @param subject
     * @return
     */
    public static Token createToken(Subject subject) {

        Token token = DefaultTokenCreator.create(ApiTenantContext.getTokenTimeout(),
                MapUtils.asMap(ArcherSecurityModule.subjectTokenAttr, subject));

        getTokenManager().create(token);

        return token;
    }

    /**
     * 销毁当前请求对应的token
     */
    public static void invalidateToken() {

        invalidateToken(ServletUtils.getCurrentRequest());
    }

    /**
     * 销毁请求对应的token
     *
     * @param request
     */
    public static void invalidateToken(HttpServletRequest request) {

        invalidateToken(request.getParameter(ArcherSecurityModule.tokenField));
    }

    public static void invalidateToken(String tokenId) {

        getTokenManager().invalidate(tokenId);
    }

    /**
     * 获得tokenManager
     *
     * @return
     */
    public static TokenManager getTokenManager() {

        return ContextUtils.getBean(TokenManager.class);
    }
}
